package main

import (
	"fmt"
	"github.com/aliyun/fc-runtime-go-sdk/fc"
	"github.com/gin-gonic/gin"
	"ocan_data_sync_task/config"
	"ocan_data_sync_task/handlers"
	"ocan_data_sync_task/models"
	"os"
)

func main() {
	// 1. 加载配置
	cfg, err := config.LoadConfig("config.json")
	if err != nil {
		panic(err)
	}

	// 2. 初始化Redis
	rdb, err := initRedis(cfg)
	if err != nil {
		panic(err)

	}

	// 3. 初始化handler
	handler := handlers.NewTaskHandler(rdb, cfg)

	// 4. 启动服务
	if os.Getenv("FC_FUNCTION_NAME") == "" {
		http(handler)
	} else {
		fc.Start(handler.HttpHandler)
	}

}

func http(handler *handlers.TaskHandler) {
	// http 测试
	r := gin.Default()

	r.POST("/create_task", func(c *gin.Context) {

		// 接收任意JSON结构
		var task models.Task
		if err := c.ShouldBindJSON(&task); err != nil {
			c.JSON(400, gin.H{"error": "无效的JSON格式"})
			return
		}
		data, err := handler.Handle(c, &task)
		if err != nil {
			fmt.Println(err)
		}
		c.JSON(200, data)
	})
	r.GET("/info/:task_id", func(c *gin.Context) {
		taskID := c.Param("task_id")

		data, err := handler.ReadResult(c, taskID)
		msg := "success"
		if err != nil {
			msg = err.Error()
		}
		c.JSON(200, models.HTTPResponse{TaskId: taskID, Code: 0, Message: msg, Data: data})
	})
	r.Run(":8080")
}
